<template>
  <div class="product-detail-container">
    <div class="common-header">
      <div class="logo">
        <img src="@/assets/logo.png" alt="宁夏枸杞农产品溯源系统" />
        <h1>商品防伪网站</h1>
      </div>
      <div class="nav-links">
<!--        <router-link to="/">首页</router-link>-->
        <router-link to="/trace">溯源查询</router-link>
      </div>
    </div>

    <div class="content">
      <div class="product-card" v-loading="loading">
        <div class="back-link">
          <router-link to="/trace">
            <i class="el-icon-arrow-left"></i> 返回溯源查询
          </router-link>
        </div>

        <h2>{{ product.productName }}</h2>

        <div class="product-image">
          <img
            :src="product.productImage || require('@/assets/logo.png')"
            @error="handleImageError"
            alt="产品图片" />
        </div>

        <!-- 添加二维码区域 -->
        <div class="qr-code-container">
          <h3>溯源二维码</h3>
          <div class="qr-code-wrapper">
            <canvas ref="qrCanvas"></canvas>
            <p class="qr-tip">扫描二维码，随时查看产品溯源信息</p>
            <el-button type="primary" size="small" @click="downloadQRCode" icon="el-icon-download">
              下载二维码
            </el-button>
          </div>
        </div>

        <div class="basic-info">
          <h3>基本信息</h3>
          <el-row :gutter="20">

            <el-col :span="12">
              <div class="info-item">
                <span class="label">产品等级：</span>
                <span class="value">{{ product.qualityLevel || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">生产批次：</span>
                <span class="value">{{ product.batchNumber || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">产地：</span>
                <span class="value">{{ product.origin || '暂无' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="source-info">
          <h3>种植信息</h3>
          <el-row :gutter="20" v-if="product.farmingDetails">
            <el-col :span="12">
              <div class="info-item">
                <span class="label">种植区域：</span>
                <span class="value">{{ product.farmingDetails.region || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">生产商：</span>
                <span class="value">{{ product.farmingDetails.farmer || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="info-item">
                <span class="label">种植环境：</span>
                <span class="value">{{ product.farmingDetails.environment || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">肥料使用：</span>
                <span class="value">{{ product.farmingDetails.fertilizer || '暂无' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">农药使用：</span>
                <span class="value">{{ product.farmingDetails.pesticide || '暂无' }}</span>
              </div>
            </el-col>
          </el-row>
          <el-empty v-else description="暂无种植信息"></el-empty>
        </div>

        <div class="trace-info">
          <h3>溯源信息</h3>
          <el-steps :active="product.steps ? product.steps.length : 0" direction="vertical" finish-status="success">
            <el-step
              v-for="(step, index) in product.steps || []"
              :key="index"
              :title="step.title"
              :description="step.time + ' - ' + step.description">
            </el-step>
          </el-steps>
        </div>

        <div class="certificate">
          <h3>质量认证</h3>
          <el-tag size="medium" type="success" v-if="product.verified">有机认证</el-tag>
          <el-tag size="medium" type="warning" v-if="product.productionStandard">{{ product.productionStandard }}</el-tag>
        </div>
      </div>
    </div>

    <div class="common-footer">
      <p>© 2025 宁夏枸杞农产品溯源系统 版权所有</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import QRCode from 'qrcode'

export default {
  name: 'ProductDetailPageView',
  data() {
    return {
      loading: true,
      product: {},
      traceCode: ''
    }
  },
  mounted() {
    // 从路由参数获取溯源码
    this.traceCode = this.$route.params.id
    if (this.traceCode) {
      this.fetchProductDetail(this.traceCode)
    } else {
      this.$message.error('无效的溯源码')
      this.loading = false
    }
  },
  methods: {
    fetchProductDetail(traceCode) {
      this.loading = true
      axios.get(`/api/trace-query/${traceCode}`)
        .then(response => {
          if (response.data.success) {
            this.product = response.data.data
            document.title = `${this.product.productName || '产品'} - 溯源详情`

            // 记录查询日志，确保使用正确的请求体格式
            this.recordQuery(traceCode)

            // 生成二维码
            this.$nextTick(() => {
              this.generateQRCode()
            })
          } else {
            this.$message.error(response.data.message || '获取产品详情失败')
          }
        })
        .catch(error => {
          console.error('获取产品详情失败', error)
          this.$message.error('获取产品详情失败，请稍后重试')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 添加记录查询方法
    recordQuery(code) {
      // 尝试记录查询，但不影响主要功能
      axios.post('/api/trace-query/record', { code })
        .catch(error => {
          console.warn('记录查询失败', error)
          // 不显示错误通知，因为这是非核心功能
        })
    },
    handleImageError(event) {
      // 当图片加载失败时，使用本地 logo 作为备用
      event.target.src = require('@/assets/logo.png')
    },
    generateQRCode() {
      if (this.$refs.qrCanvas && this.traceCode) {
        // 构建完整的溯源URL
        let traceUrl = ''

        // 获取当前站点的基础URL
        const protocol = window.location.protocol
        const host = window.location.host

        // 构建完整的溯源URL (使用绝对URL)
        traceUrl = `${protocol}//${host}/trace/${this.traceCode}`

        console.log('生成溯源二维码URL:', traceUrl)

        // 设置QR码的属性
        const options = {
          width: 200,
          margin: 2,
          color: {
            dark: '#303133',
            light: '#ffffff'
          }
        }

        // 生成二维码
        QRCode.toCanvas(this.$refs.qrCanvas, traceUrl, options, (error) => {
          if (error) {
            console.error('二维码生成失败:', error)
          } else {
            console.log('二维码生成成功')
          }
        })
      }
    },
    downloadQRCode() {
      if (!this.$refs.qrCanvas) return

      try {
        // 获取二维码的数据URL
        const dataUrl = this.$refs.qrCanvas.toDataURL('image/png')

        // 创建下载链接
        const link = document.createElement('a')
        link.href = dataUrl
        link.download = `${this.product.productName || '产品'}_溯源码.png`

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('二维码已下载')
      } catch (error) {
        console.error('下载二维码失败:', error)
        this.$message.error('下载二维码失败')
      }
    }
  }
}
</script>

<style scoped>
.product-detail-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.common-header {
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 40px;
  margin-right: 10px;
}

.logo h1 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.nav-links {
  display: flex;
  gap: 20px;
}

.nav-links a {
  color: #666;
  text-decoration: none;
}

.content {
  flex: 1;
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
}

.product-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  min-height: 400px;
}

.back-link {
  margin-bottom: 20px;
}

.back-link a {
  color: #409EFF;
  text-decoration: none;
}

.product-card h2 {
  margin-bottom: 20px;
  text-align: center;
  color: #303133;
}

.product-image {
  text-align: center;
  margin-bottom: 20px;
}

.product-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

/* 二维码样式 */
.qr-code-container {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
}

.qr-code-container h3 {
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 15px;
  border-left: 3px solid #409EFF;
  padding-left: 10px;
  text-align: left;
}

.qr-code-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.qr-code-wrapper canvas {
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.qr-tip {
  color: #606266;
  font-size: 14px;
  margin-top: 10px;
}

.basic-info, .source-info, .trace-info, .certificate {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.basic-info h3, .source-info h3, .trace-info h3, .certificate h3 {
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 15px;
  border-left: 3px solid #409EFF;
  padding-left: 10px;
}

.info-item {
  margin-bottom: 10px;
}

.label {
  color: #606266;
  font-weight: bold;
}

.value {
  color: #303133;
}

.certificate {
  display: flex;
  gap: 10px;
  align-items: center;
}

.certificate h3 {
  margin-bottom: 0;
  margin-right: 10px;
}

.common-footer {
  background-color: #324057;
  color: #eee;
  text-align: center;
  padding: 15px;
  font-size: 14px;
}
</style>
